package com.deyou.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.deyou.Constants;
import com.deyou.R;
import com.deyou.activity.FeedBackActivity;
import com.deyou.activity.HouseCalenderListActivity;
import com.deyou.activity.HouseResourceListActivity;
import com.deyou.activity.IdentityVerifyActivity;
import com.deyou.activity.LoginActivity;
import com.deyou.activity.MyTravelListActivity;
import com.deyou.activity.OrderListActivity;
import com.deyou.activity.PaymentTypeActivity;
import com.deyou.activity.SettingActivity;
import com.deyou.activity.UserInfoActivity;
import com.deyou.base.BaseFragment;
import com.deyou.callback.ServerApi;
import com.deyou.model.LzyResponse;
import com.deyou.model.UserInfoBean;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.Logger;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.deyou.widget.CircleImageView;
import com.google.gson.jpush.reflect.TypeToken;
import com.yanzhenjie.album.Album;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.callback.SaveCallback;

import java.lang.reflect.Type;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

public class PersonalCenterFragment extends BaseFragment {

    private static PersonalCenterFragment fragment;
    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.iv_user_avatar)
    CircleImageView ivUserAvatar;
    @BindView(R.id.iv_default_avatar)
    ImageView ivDefaultAvatar;
    @BindView(R.id.tv_goto_login)
    TextView tvGotoLogin;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.my_travel_layout)
    RelativeLayout myTravelLayout;
    @BindView(R.id.share_app_layout)
    RelativeLayout shareAppLayout;
    @BindView(R.id.feed_back_layout)
    RelativeLayout feedBackLayout;
    @BindView(R.id.payment_type_layout)
    RelativeLayout paymentTypeLayout;
    @BindView(R.id.user_name_layout)
    LinearLayout userNameLayout;
    @BindView(R.id.btn_tobe_landlord)
    TextView btnTobeLandlord;
    @BindView(R.id.btn_identity_verify)
    TextView btnIdentityVerify;
    @BindView(R.id.user_permission_layout)
    LinearLayout userPermissionLayout;
    @BindView(R.id.calender_setting_layout)
    LinearLayout calenderSettingLayout;
    @BindView(R.id.order_manager_layout)
    LinearLayout orderManagerLayout;
    @BindView(R.id.my_house_layout)
    LinearLayout myHouseLayout;
    @BindView(R.id.landlord_permission_layout)
    LinearLayout landlordPermissionLayout;

    Unbinder unbinder;
    private int verifyStatus = 0;

    private Context mContext;

    public PersonalCenterFragment() {
        // Required empty public constructor
    }

    public static PersonalCenterFragment newInstance(String param1, String param2) {
        fragment = new PersonalCenterFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        this.mContext = context;
        super.onAttach(context);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal_center, container, false);
        return view;
    }

    @Override
    protected void initData() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_setting, R.id.iv_user_avatar, R.id.iv_default_avatar, R.id.tv_goto_login, R.id.tv_user_name,
            R.id.my_travel_layout, R.id.share_app_layout, R.id.feed_back_layout, R.id.btn_tobe_landlord, R.id.btn_identity_verify,
            R.id.calender_setting_layout, R.id.order_manager_layout, R.id.my_house_layout, R.id.payment_type_layout})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.iv_setting:
                AndroidUtils.startNextActivity(getActivity(), SettingActivity.class, null, false);
                break;
            case R.id.iv_user_avatar:
                if (TextUtils.isEmpty(SPUtils.getStringByKey(getActivity(), Constants.UserId))) {
                    AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                    return;
                }
//                callAlbum();
                AndroidUtils.startNextActivity(getActivity(), UserInfoActivity.class, null, false);
                break;
            case R.id.iv_default_avatar:
                AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                break;
            case R.id.tv_goto_login:
                AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                break;
            case R.id.tv_user_name:
                break;
            case R.id.my_travel_layout:
                if (TextUtils.isEmpty(SPUtils.getStringByKey(getActivity(), Constants.UserId))) {
                    AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                    return;
                }
                AndroidUtils.startNextActivity(getActivity(), MyTravelListActivity.class, null, false);
                break;
            case R.id.share_app_layout:
                break;
            case R.id.feed_back_layout:
                AndroidUtils.startNextActivity(getActivity(), FeedBackActivity.class, null, false);
                break;
            case R.id.btn_tobe_landlord:
                if (TextUtils.isEmpty(SPUtils.getStringByKey(getActivity(), Constants.UserId))) {
                    AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                    return;
                }
                break;
            case R.id.btn_identity_verify:
                if (TextUtils.isEmpty(SPUtils.getStringByKey(getActivity(), Constants.UserId))) {
                    AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                    return;
                }
                bundle.putInt("verify_status", verifyStatus);
                AndroidUtils.startNextActivity(getActivity(), IdentityVerifyActivity.class, bundle, false);
                break;
            case R.id.calender_setting_layout:
                if (TextUtils.isEmpty(SPUtils.getStringByKey(getActivity(), Constants.UserId))) {
                    AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                    return;
                }
                AndroidUtils.startNextActivity(getActivity(), HouseCalenderListActivity.class, null, false);
                break;
            case R.id.order_manager_layout:
                if (TextUtils.isEmpty(SPUtils.getStringByKey(getActivity(), Constants.UserId))) {
                    AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                    return;
                }
                AndroidUtils.startNextActivity(getActivity(), OrderListActivity.class, null, false);
                break;
            case R.id.my_house_layout:
                if (TextUtils.isEmpty(SPUtils.getStringByKey(getActivity(), Constants.UserId))) {
                    AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null, false);
                    return;
                }
                AndroidUtils.startNextActivity(getActivity(), HouseResourceListActivity.class, null, false);
                break;
            case R.id.payment_type_layout:
                AndroidUtils.startNextActivity(getActivity(), PaymentTypeActivity.class, null, false);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(SPUtils.getStringByKey(getActivity(), Constants.UserId))) {
            getUserInfo();
//            dealUserInfo(true);
        } else {
            myTravelLayout.setVisibility(View.GONE);
            landlordPermissionLayout.setVisibility(View.GONE);
            userPermissionLayout.setVisibility(View.GONE);
            ivUserAvatar.setVisibility(View.GONE);
            userNameLayout.setVisibility(View.GONE);
            ivDefaultAvatar.setVisibility(View.VISIBLE);
            tvGotoLogin.setVisibility(View.VISIBLE);
            paymentTypeLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 处理用户信息
     * @param needRefreshInfo
     */
    private void dealUserInfo(boolean needRefreshInfo) {
        UserInfoBean user = UserInfoBean.where("userId = ?", SPUtils.getStringByKey(getActivity(), Constants.UserId)).findFirst(UserInfoBean.class);
        if (null != user) {
            if (user.getUserType() == 1) { // 个人用户,且不是调用用户信息后进入此处，则重新调用接口获取用户信息
                if (needRefreshInfo)
                    getUserInfo();
                landlordPermissionLayout.setVisibility(View.VISIBLE); //test
                userPermissionLayout.setVisibility(View.VISIBLE);
                btnTobeLandlord.setVisibility(View.VISIBLE);
                btnIdentityVerify.setVisibility(View.VISIBLE); // test
                paymentTypeLayout.setVisibility(View.VISIBLE); // test
            } else if (user.getUserType() == 2) {  // 房东用户
                landlordPermissionLayout.setVisibility(View.VISIBLE);
                paymentTypeLayout.setVisibility(View.VISIBLE);
                if (user.getUserAuthentication() == 0) {  // 房东未进行身份认证
                    userPermissionLayout.setVisibility(View.VISIBLE);
                    btnTobeLandlord.setVisibility(View.GONE);
                    btnIdentityVerify.setVisibility(View.VISIBLE);
                } else { // 房东已身份认证
                    userPermissionLayout.setVisibility(View.GONE);
                }
            }
            verifyStatus = user.getUserAuthentication();
            tvUserName.setText(!TextUtils.isEmpty(user.userNickname) ? user.userNickname :
                    !TextUtils.isEmpty(user.userName) ? user.userName :
                            !TextUtils.isEmpty(user.userRealname) ? user.userRealname :
                                    !TextUtils.isEmpty(user.userLogin) ? user.userLogin : "竭嘶底里的幸福");
            new GlideImageLoader().displayImage(getActivity(), user.userPic, ivUserAvatar);
            ivUserAvatar.setVisibility(View.VISIBLE);
            userNameLayout.setVisibility(View.VISIBLE);
            ivDefaultAvatar.setVisibility(View.GONE);
            tvGotoLogin.setVisibility(View.GONE);
            myTravelLayout.setVisibility(View.VISIBLE);
        } else {
            myTravelLayout.setVisibility(View.GONE);
            landlordPermissionLayout.setVisibility(View.GONE);
            userPermissionLayout.setVisibility(View.GONE);
            ivUserAvatar.setVisibility(View.GONE);
            userNameLayout.setVisibility(View.GONE);
            ivDefaultAvatar.setVisibility(View.VISIBLE);
            tvGotoLogin.setVisibility(View.VISIBLE);
            paymentTypeLayout.setVisibility(View.GONE);
        }
    }

    private void getUserInfo() {
        JSONObject object = new JSONObject();
        try {
            object.put("userId", SPUtils.getStringByKey(getActivity(), Constants.UserId));
            String paramJson = object.toString();

            Type type = new TypeToken<LzyResponse<UserInfoBean>>() {}.getType();
            ServerApi.<LzyResponse<UserInfoBean>>getData(type, Urls.getUserInfo, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
//                        showLoading();
                        }
                    })//
                    .map(new Function<LzyResponse<UserInfoBean>, UserInfoBean>() {
                        @Override
                        public UserInfoBean apply(@NonNull LzyResponse<UserInfoBean> response) throws Exception {
                            return response.data;
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<UserInfoBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull UserInfoBean response) {
                            insertUserInfoToDB(response);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            handler.sendEmptyMessage(1);
                        }

                        @Override
                        public void onComplete() {
//                        dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据库保存用户信息
     *
     * @param model
     */
    private void insertUserInfoToDB(UserInfoBean model) {
        if (null != model) {
            UserInfoBean user = new UserInfoBean();
            user.setUserId(model.userId);
            user.setUserName(model.userName);
            user.setUserNickname(model.userNickname);
            user.setUserSex(model.userSex);
            user.setUserLogin(model.userLogin);
            user.setUserPassword(model.userPassword);
            user.setUserRegisterType(model.userRegisterType);
            user.setUserCountrynum(model.userCountrynum);
            user.setUserIntroduction(model.userIntroduction);
            user.setUserWechat(model.userWechat);
            user.setUserPic(model.userPic);
            user.setUserType(model.userType);
            user.setUserAuthentication(model.userAuthentication);
            user.setUserRealname(model.userRealname);
            user.setUserCard(model.userCard);
            user.setUserCardPic(model.userCardPic);
            user.setUserSatisfaction(model.userSatisfaction);
            user.setUserRecoveryrate(model.userRecoveryrate);
            user.setUserHobby(model.userHobby);
            user.setUserPhone(model.userPhone);
            user.setUserSesameCredit(model.userSesameCredit);
            user.setUserJChatAppKey(model.userJChatAppKey);
            user.setUserJChatName(model.userJChatName);
            user.setUserRegionName(model.userRegionName);
            user.setUserRegion(model.userRegion);
            user.saveOrUpdateAsync("userId = ?", model.getUserId()).listen(new SaveCallback() {
                @Override
                public void onFinish(boolean success) {
                    handler.sendEmptyMessage(1);
                }
            });
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    dealUserInfo(false);
                    break;
                case 2:
                    break;
            }
        }
    };
}
